package com.scaffold.myproject.web.controller;

import com.scaffold.myproject.common.Result;
import com.scaffold.myproject.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/oss")
public class OssUploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 上传 MultipartFile 文件到 OSS 公有桶
     *
     * @param file MultipartFile 文件
     * @param folder 上传目录（例如 "images"）
     * @return 上传后的 OSS 路径
     */
    @PostMapping("/upload")
    public Result<String> uploadMultipartFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "folder", defaultValue = "default") String folder) {
        try {
            String path = aliOSSUtils.upload(file, folder);
            return Result.of(path);
        } catch (IOException e) {
            log.error("上传失败", e);
            return Result.of(500,"上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传本地文件到 OSS 公有桶
     *
     * @param localFilePath 本地文件绝对路径
     * @param folder 上传目录
     * @return OSS 路径
     */
    @PostMapping("/uploadLocal")
    public Result<String> uploadLocalFile(
            @RequestParam("localFilePath") String localFilePath,
            @RequestParam(value = "folder", defaultValue = "default") String folder) {
        File file = new File(localFilePath);
        if (!file.exists() || !file.isFile()) {
            return Result.of(500,"本地文件不存在或不是文件");
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            String fileName = file.getName();
            String path = aliOSSUtils.upload(folder, fileName, fis, false);
            return Result.of(aliOSSUtils.getFullUrl(path, false));
        } catch (IOException e) {
            log.error("上传本地文件失败", e);
            return Result.of(500,"上传失败: " + e.getMessage());
        }
    }
}
